package com.zjsru.oneday202208;

/**
 * @Author: likew
 * @Date: 2022/8/10 求解方程,只有“+”“-”两个符号
 * <p>
 * 输入: equation = "x+5-3+x=6+x-2" 输出: "x=2"
 * <p>
 * 输入: equation = "x=x" 输出: "Infinite solutions"
 * <p>
 * 输入: equation = "2x=x" 输出: "x=0"
 */
public class SolveEquation {
    
    public String solveEquation(String equation) {
        int x = 0, num = 0, n = equation.length();
        char[] chars = equation.toCharArray();
        for (int i = 0, op = 1; i < n; ) {
            if (chars[i] == '+') {
                op = 1;
                i++;
            } else if (chars[i] == '-') {
                op = -1;
                i++;
            } else if (chars[i] == '=') {
                x *= -1;
                num *= -1;
                op = 1;
                i++;
            } else {
                int j = i;
                while (j < n && chars[j] != '+' && chars[j] != '-' && chars[j] != '=') {
                    j++;
                }
                if (chars[j - 1] == 'x') {
                    x += (i < j - 1 ? Integer.parseInt(equation.substring(i, j - 1)) : 1) * op;
                } else {
                    num += Integer.parseInt(equation.substring(i, j)) * op;
                }
                i = j;
            }
        }
        if (x == 0) {
            return num == 0 ? "Infinite solutions" : "No solution";
        } else {
            return "x=" + (num / -x);
        }
    }
    
    public static void main(String[] args) {
        SolveEquation solveEquation = new SolveEquation();
        String equation = "x+5-3+x=6+x-2";
        System.out.println(solveEquation.solveEquation(equation));
    }
}
